using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Comteck.Dto.Orders;

namespace Comteck.Ktt.Services.Plugs.EMS {
  /// <summary>
  /// 
  /// </summary>
  public class EMSHelper {
    /// <summary>
    /// 获取面单号
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>

    public static async Task<AjaxResponse<M020003Reponse>> GetWayBillNoAsync(SaleOrderDto model, EMSClientOptions options, UserAddress sender, UserAddress pickUp) {
      var client = EMSClientBulider.Bulid(x => {
        x.BaseUrl = options.BaseUrl;
        x.ApiCode = ApiCodeEnum.APICODE_020003;
        x.SenderNo = options.SenderNo; // 协议客户
        x.Authorization = options.Authorization; // 授权码
        x.Key = options.Key; // 签名秘钥
      });


      var requestModel = new M020003Request {
        CreatedTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
        LogisticsOrderNo = model.Code, //订单号
        ContentsAttribute = "3", // 物品
        BizProductNo = "1", //1.特快专递  2.快递包裹 3.到付 9.即日 10.电商标快 11.标准快递
        EcommerceUserId = model.Code,
        Receiver = new UserAddress {
          Phone = model.RecipientPhone,
          Address = model.RecipientAddress.Replace($"{model.Province}{model.City}{model.District}", ""),
          Prov = model.Province,
          City = model.City,
          County = model.District,
          Mobile = model.RecipientPhone,
          Name = model.Recipient
        },
        //Sender = new UserAddress {
        //  Phone = "15824138888",
        //  Address = "118水果团",
        //  City = "杭州市",
        //  County = "萧山区",
        //  Prov = "浙江省",
        //  Name = "118水果团",
        //  Mobile = "15824138888"
        //},
        Sender = sender,
        Pickup = pickUp,
        Cargos = model.DetailList.Select(x => new CargosItem {
          CargoName = x.ProductName
        }).ToList()
      };

      var request = new List<M020003Request> { requestModel };
      var result = await client.ExecuteAsync<List<M020003Request>, M020003Reponse>(Guid.NewGuid(), request);

      if (result.RetCode == "00000" && result.Success) {
        return new AjaxResponse<M020003Reponse>() {
          Code = 1,
          Data = result.RetBodyObject
        };
      } else {
        return new AjaxResponse<M020003Reponse>() {
          Code = 0,
          Message = result.RetMsg
        };
      }
    }

    /// <summary>
    /// 订单取消接口
    /// </summary>
    /// <param name="model"></param>
    /// <param name="options"></param>
    /// <returns></returns>
    public static async Task<AjaxResponse> CancelWayBillNoAsync(M020006Request model, EMSClientOptions options) {
      var client = EMSClientBulider.Bulid(x => {
        x.BaseUrl = options.BaseUrl;
        x.ApiCode = ApiCodeEnum.APICODE_020006;
        x.SenderNo = options.SenderNo; // 协议客户
        x.Authorization = options.Authorization; // 授权码
        x.Key = options.Key; // 签名秘钥
      });

      var result = await client.ExecuteAsync<M020006Request, string>(Guid.NewGuid(), model);

      if (result.RetCode == "00000" && result.Success) {
        return new AjaxResponse() {
          Code = 1,
          Data = result.RetBodyObject
        };
      } else {
        return new AjaxResponse() {
          Code = 0,
          Message = result.RetMsg
        };
      }
    }


    /// <summary>
    /// 获取运单号轨迹
    /// </summary>
    /// <param name="model"></param>
    /// <param name="options"></param>
    /// <returns></returns>
    public static async Task<AjaxResponse<M040001Response>> GetWayBillNoPathAsync(M040001Request model, EMSClientOptions options) {
      var client = EMSClientBulider.Bulid(x => {
        x.BaseUrl = options.BaseUrl;
        x.ApiCode = ApiCodeEnum.APICODE_040001;
        x.SenderNo = options.SenderNo; // 协议客户
        x.Authorization = options.Authorization; // 授权码
        x.Key = options.Key; // 签名秘钥
      });

      var result = await client.ExecuteAsync<M040001Request, M040001Response>(Guid.NewGuid(), model);

      if (result.RetCode == "00000" && result.Success) {
        var emsResult = new AjaxResponse<M040001Response>() {
          Code = 1,
          Data = result.RetBodyObject
        };

        // 查询
        var items = emsResult.Data.ResponseItems ?? new List<M040001ResponseItem>();
        if (items.FirstOrDefault(x => x.OpCode == "704") is M040001ResponseItem item1) {
          emsResult.Data.DeliveryStatus = EnumDeliveryStatus.投递成功;
          emsResult.Data.DeliveryDesc = item1.OpDesc;
        } else if (items.FirstOrDefault(x => x.OpCode == "705") is M040001ResponseItem item2) {
          emsResult.Data.DeliveryStatus = EnumDeliveryStatus.投递失败;
          emsResult.Data.DeliveryDesc = item2.OpDesc;
        } else if (items.IsNotNullOrEmpty()) {
          var lastItem = items.Last();
          emsResult.Data.DeliveryStatus = EnumDeliveryStatus.投递中;
          emsResult.Data.DeliveryDesc = lastItem.OpDesc;
        }

        return emsResult;
      } else {
        return new AjaxResponse<M040001Response>() {
          Code = 0,
          Message = result.RetMsg
        };
      }
    }
  }
}
